package com.xjc.agent.core.util;

import java.io.File;
import java.net.URL;
import java.util.Objects;

/**
 * @author: 谢君臣
 * @Date: 2023/1/8-15:26
 * @version: 1.0
 * @function:
 */
public class LoaderUtil {
    public static URL[] findJar(String agentPath, String libPath, String confPath) {
//        String root = findRoot(agentPath);
        String root = agentPath;
        URL[] urls = null;
        String lib = root + libPath;
        File folder = new File(lib);
        if (folder.exists() && folder.isDirectory()) {
            File[] files = folder.listFiles();
            urls = new URL[files.length];
            for (int i = 0; i < files.length; i++) {
                try {
                    urls[i] = files[i].toURI().toURL();
                } catch (Exception ex) {
                    System.out.println(" agent class loader jar has error:" + ex.getMessage());
                }
            }
        }
        if (urls==null)
            return new URL[0];
        else
            return urls;
    }

    private static String findRoot(String agentPath) {
        if (Objects.nonNull(agentPath) && agentPath.length() > 0) {
            int index = agentPath.lastIndexOf(File.separator);
            return index == -1 ? agentPath : agentPath.substring(0, index);
        }
        return "";
    }
}
